﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Allegro.Mathlib
{
    public static partial class Statistics
    {
        /// <summary>
        /// Inverse errf:
        /// http://homepages.physik.uni-muenchen.de/~Winitzki/erf-approx.pdf
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static double InvErf(double x)
        {
            const double a = 0.147;
            double log1 = Math.Log(1.0 - x * x);
            double z = (2.0 / (Math.PI * a) + log1 / 2.0);

            double inv = -2.0 / (Math.PI * a) - log1 / 2.0 + Math.Sqrt(z * z - log1 / a);
            if(x > 0.5)
                inv = Math.Sqrt(inv);
            else if(x < 0.5)
                inv = -Math.Sqrt(inv);
            else
            {
                inv = 0.0;
            }
            return inv;
        }
    }
}
